<template>
  <a-row id="globalHeader" align="center" :wrap="false">
    <a-col flex="auto">
      <a-menu
        mode="horizontal"
        :default-selected-keys="['1']"
        :selected-keys="selectedKeys"
        @menu-item-click="toMenuClick"
      >
        <a-menu-item
          key="0"
          :style="{ padding: 0, marginRight: '38px' }"
          disabled
        >
          <div class="title-bar">
            <img class="logo" src="../assets/huiji.png" />
            <div class="title">Yang OJ</div>
          </div>
        </a-menu-item>
        <a-menu-item v-for="item in visibleRoutes" :key="item.path">
          {{ item.name }}
        </a-menu-item>
      </a-menu>
    </a-col>

    <a-dropdown trigger="hover">
      <a-avatar shape="circle">
        <template v-if="loginUser.userRole !== ACCESS_ENUM.NOT_LOGIN">
          <template v-if="loginUser.userAvatar">
            <img alt="avatar" :src="loginUser.userAvatar" class="userAvatar" />
          </template>
          <template v-else>
            <a-avatar>
              <IconUser />
            </a-avatar>
          </template>
        </template>
        <template v-else>
          <a-avatar>未登录</a-avatar>
        </template>
      </a-avatar>

      <template #content>
        <template v-if="loginUser.userRole !== ACCESS_ENUM.NOT_LOGIN">
          <a-doption>
            <template #icon>
              <icon-idcard />
            </template>
            <template #default>
              <a-anchor-link @click="detail(loginUser.id)"
                >个人信息
              </a-anchor-link>
            </template>
          </a-doption>
          <a-doption>
            <template #icon>
              <icon-poweroff />
            </template>
            <template #default>
              <a-anchor-link @click="logout">退出登录</a-anchor-link>
            </template>
          </a-doption>
        </template>
        <template v-else>
          <a-doption>
            <template #icon>
              <icon-user />
            </template>
            <template #default>
              <a-anchor-link href="/user/login">登录</a-anchor-link>
            </template>
          </a-doption>
          <a-doption>
            <template #icon>
              <icon-user-add />
            </template>
            <template #default>
              <a-anchor-link href="/user/register">注册</a-anchor-link>
            </template>
          </a-doption>
        </template>
      </template>
    </a-dropdown>

    <a-col flex="100px" style="margin-left: 10px">
      <div>{{ store.state.user?.loginUser?.userName ?? "未登录" }}</div>
    </a-col>
  </a-row>

  <a-modal
    width="40%"
    :visible="visible"
    title="个人信息"
    placement="right"
    @ok="handleOk"
    @cancel="closeModel"
    unmountOnClose
  >
    <div style="text-align: center">
      <a-avatar :size="70" shape="circle">
        <img alt="头像" :src="userInfo?.userAvatar" />
      </a-avatar>
    </div>
    <div style="margin-top: 20px"></div>
    <a-form
      label-align="right"
      title="个人信息"
      style="max-width: 500px; margin: 0 auto"
    >
      <a-form-item field="账号" label="账号 :">
        <a-input
          disabled
          v-model="userInfo.userAccount"
          placeholder="请输入账号"
        />
      </a-form-item>
      <a-form-item field="昵称" label="昵称 :">
        <a-input v-model="userInfo.userName" placeholder="请输入用户昵称" />
      </a-form-item>
      <a-form-item field="userAvatar" label="修改头像 :">
        <a-upload
          action="/"
          :fileList="file ? [file] : []"
          :show-file-list="false"
          @change="onChange"
          :custom-request="uploadAvatar"
        >
          <template #upload-button>
            <a-avatar :size="70" shape="square">
              <img alt="头像" :src="userInfo?.userAvatar" />
              <div class="arco-upload-list-picture-mask">
                <IconEdit />
              </div>
            </a-avatar>
          </template>
        </a-upload>
      </a-form-item>
      <a-form-item field="userProfile" label="简介 :">
        <a-textarea v-model="userInfo.userProfile" placeholder="请输入简介" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { routes } from "@/router/routes";
import { useRoute, useRouter } from "vue-router";
import { computed, ref } from "vue";
import { useStore } from "vuex";
import checkAccess from "@/access/checkAccess";
import ACCESS_ENUM from "@/access/accessEnum";
import {
  FileControllerService,
  LoginUserVO,
  UserControllerService,
  UserVO,
} from "../../generated";
import { FileItem, Message } from "@arco-design/web-vue";

const router = useRouter();
const store = useStore();

// 获取登录用户信息
const loginUser: LoginUserVO = computed(
  () => store.state.user?.loginUser
) as LoginUserVO;

const visibleRoutes = computed(() => {
  return routes.filter((item, index) => {
    if (item.meta?.hideInMenu) {
      return false;
    }
    //根据用户权限过滤菜单
    if (
      !checkAccess(store.state.user.loginUser, item?.meta?.access as string)
    ) {
      return false;
    }
    return true;
  });
});

//默认跳转到主页
const selectedKeys = ref(["/"]);

//退出登录，返回登录页面
const logout = () => {
  UserControllerService.userLogoutUsingPost();
  loginView();
  // location.reload();
};

/**
 * 跳转到登录页面
 */
const loginView = () => {
  router.push({
    path: `/user/login`,
  });
};

//跳转菜单后，记录path到selectedKeys中记录，下次刷新时仍然是这个页面
router.afterEach((to, from, failure) => {
  selectedKeys.value = [to.path];
});

/**
 * 打开弹窗,获取到用户信息
 */
const userInfo = ref<UserVO>();
const visible = ref(false);
const detail = async (userId: any) => {
  const res = await UserControllerService.getUserVoByIdUsingGet(userId);
  userInfo.value = res.data;
  visible.value = true;
};

setTimeout(() => {
  store.dispatch("user/getLoginUser", {
    userName: "YuYoung",
    userRole: ACCESS_ENUM.ADMIN,
  });
}, 1000);

const toMenuClick = (key: string) => {
  router.push({
    path: key,
  });
};

/**
 * 确定修改个人按钮
 */
const handleOk = async () => {
  const res = await UserControllerService.updateMyUserUsingPost(userInfo.value);
  if (res.code === 0) {
    Message.success("更新成功！");
    visible.value = false;
    // 刷新登录用户的信息
    setTimeout(() => {
      store.dispatch("user/getLoginUser", {
        userName: "YuYoung",
        userRole: ACCESS_ENUM.ADMIN,
      });
    }, 1000);
  } else {
    Message.error("更新失败！", res.msg);
  }
};
//关闭弹窗
const closeModel = () => {
  visible.value = false;
};
// 从表单中获取的用户头像
let userAvatarImg = userInfo.value?.userAvatar;

const file = ref();
/**
 * 上传头像
 */
const uploadAvatar = async () => {
  const res = await FileControllerService.uploadFileUsingPost(
    "user_avatar",
    file?.value.file
  );
  if (res.code === 0) {
    userAvatarImg = res.data;
    userInfo.value.userAvatar = userAvatarImg;
    Message.success("上传成功");
  } else {
    Message.error("上传失败！" + res.data);
  }
};

const onChange = async (_: never, currentFile: FileItem) => {
  file.value = {
    ...currentFile,
  };
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.title-bar {
  display: flex;
  align-items: center;
}

.logo {
  height: 45px;
}

.title {
  color: #444;
  margin-left: 16px;
}
</style>
